 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=164 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Template method
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Template method</div>

<div class='main-body'>
 
<br>Template methods :
<ul>
<li>are used in most abstract base classes</li>
<li>are perhaps the most commonly used of all design patterns</li>
<li>define the general steps of a method, while deferring the implementation
of at least one of the steps to a concrete subclass</li>
</ul>
<b>Example</b>

<p><tt>TxTemplate</tt> is an abstract base class which defines a template
method for executing multiple database operations within a transaction.
It is useful to define these steps in one place. The alternative is to
repeat the same structure every time a transaction is required. As usual,
such code repetition should always be aggressively eliminated.
<p>The <tt>executeTx</tt> method is the template method. It is <tt>final</tt>,
and defines the general outline of how to execute a database transaction.
The specific database actions to be taken are implemented by calling the
<tt>abstract</tt>
method <tt>executeMultipleSqls</tt>.
<br>
<PRE>


<span class='keyword'>import</span> java.sql.*;
<span class='keyword'>import</span> java.util.logging.*;

<span class='keyword'>import</span> hirondelle.web4j.BuildImpl;
<span class='keyword'>import</span> hirondelle.web4j.util.Util;
<span class='keyword'>import</span> hirondelle.web4j.util.Consts;

<span class='comment'>/** 
* Template for executing a local, non-distributed transaction versus a single database,  
* using a single connection.
*
* &lt;P&gt;This abstract base class implements the template method design pattern.  
*/</span>
<span class='keyword'>public</span> <span class='keyword'>abstract</span> <span class='keyword'>class</span> TxTemplate <span class='keyword'>implements</span> Tx {
  
  <span class='comment'>//..elided
</span>  
  <span class='comment'>/**
  * &lt;b&gt;Template&lt;/b&gt; method calls the abstract method {@link #executeMultipleSqls}.
  * &lt;P&gt;Returns the same value as &lt;tt&gt;executeMultipleSqls&lt;/tt&gt;.
  *
  * &lt;P&gt;A &lt;tt&gt;rollback&lt;/tt&gt; is performed if &lt;tt&gt;executeMultipleSqls&lt;/tt&gt; throws 
  * a {@link SQLException} or
  * {@link DAOException}, or if {@link #executeMultipleSqls(Connection)} returns 
  * {@link #BUSINESS_RULE_FAILURE}.  
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>int</span> executeTx() <span class='keyword'>throws</span> DAOException {
    <span class='keyword'>int</span> result = <span class='literal'>0</span>;
    fLogger.fine(
      <span class='literal'>"Editing within a local transaction, with isolation level : "</span> + fTxIsolationLevel
    );
    ConnectionSource connSource = BuildImpl.forConnectionSource();
    <span class='keyword'>if</span>(Util.textHasContent(fDatabaseName)){
      fConnection = connSource.getConnection(fDatabaseName);
    }
    <span class='keyword'>else</span> {
      fConnection = connSource.getConnection();
    }
    
    <span class='keyword'>try</span> {
      TxIsolationLevel.set(fTxIsolationLevel, fConnection);
      startTx();
      result = executeMultipleSqls(fConnection);
      endTx(result);
    }
    <span class='keyword'>catch</span>(SQLException rootCause){
      fLogger.fine(<span class='literal'>"Transaction throws SQLException."</span>);
      rollbackTx();
      String message = 
        <span class='literal'>"Cannot execute edit. ErrorId code : "</span> +  rootCause.getErrorCode() + 
        Consts.SPACE + rootCause
      ;
      <span class='keyword'>if</span> (rootCause.getErrorCode() == DbConfig.getErrorCodeForDuplicateKey().intValue()){
        <span class='keyword'>throw</span> <span class='keyword'>new</span> DuplicateException(message, rootCause);
      }
      <span class='keyword'>throw</span> <span class='keyword'>new</span> DAOException(message, rootCause);
    }
    <span class='keyword'>catch</span> (DAOException ex){
      fLogger.fine(<span class='literal'>"Transaction throws DAOException."</span>);
      rollbackTx();
      <span class='keyword'>throw</span> ex;
    }
    <span class='keyword'>finally</span> {
      DbUtil.logWarnings(fConnection);
      DbUtil.close(fConnection);
    }
    fLogger.fine(<span class='literal'>"Total number of edited records: "</span> + result);
    <span class='keyword'>return</span> result;
  }

  <span class='comment'>/**
  * Execute multiple SQL operations in a single local transaction.
  *
  * &lt;P&gt;This method returns the number of records edited. If a business rule 
  * determines that a 
  * rollback should be performed, then it is recommended that the special value
  * {@link #BUSINESS_RULE_FAILURE} be returned by the implementation. This will
  *  signal to 
  * {@link #executeTx()} that a rollback must be performed. (Another option for 
  * signalling that a rollback is desired is to throw a checked exception.)  
  *
  * &lt;P&gt;&lt;em&gt;Design Note&lt;/em&gt;: allowing &lt;tt&gt;SQLException&lt;/tt&gt; in the &lt;tt&gt;throws&lt;/tt&gt; 
  * clause simplifies the implementor significantly, since no &lt;tt&gt;try-catch&lt;/tt&gt; 
  * blocks are needed. Thus, the caller has simple, "straight-line" code.
  *
  * @param aConnection must be used by all SQL statements participating in this 
  * transaction
  * @return number of records edited by this operation. Implementations may return
  * {@link #BUSINESS_RULE_FAILURE} if there is a business rule failure. 
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>abstract</span> <span class='keyword'>int</span> executeMultipleSqls(
    Connection aConnection
  ) <span class='keyword'>throws</span> SQLException, DAOException;
  
  <span class='comment'>/**
  * Value {@value}. Special value returned by 
  * {@link #executeMultipleSqls(Connection)} to indicate that  
  * a business rule has been violated. Such a return value indicates to this class
  * that a rollback must be performed.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>int</span> BUSINESS_RULE_FAILURE = -<span class='literal'>1</span>;
  
  <span class='comment'>// PRIVATE //
</span>  
  <span class='comment'>/**
  * The connection through which all SQL statements attached to this 
  * transaction are executed. This connection may be for the default 
  * database, or any other defined database. See {@link #fDatabaseName}.
  */</span>
  <span class='keyword'>private</span> Connection fConnection;
  
  <span class='comment'>/** 
  * Identifier for a non-default database. The connection taken from the default
  * database only if this item has no content. 
  */</span>
  <span class='keyword'>private</span> String fDatabaseName;
  
  <span class='comment'>/**
  * The transaction isolation level, defaults to level configured in 
  * &lt;tt&gt;web.xml&lt;/tt&gt;.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>final</span> TxIsolationLevel fTxIsolationLevel;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>boolean</span> fOFF = <span class='keyword'>false</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>boolean</span> fON = <span class='keyword'>true</span>;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Logger fLogger = Util.getLogger(TxTemplate.<span class='keyword'>class</span>);  

  <span class='keyword'>private</span> <span class='keyword'>void</span> startTx() <span class='keyword'>throws</span> SQLException {
    fConnection.setAutoCommit(fOFF);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>void</span> endTx(<span class='keyword'>int</span> aNumEdits) <span class='keyword'>throws</span> SQLException, DAOException {
    <span class='keyword'>if</span> ( BUSINESS_RULE_FAILURE == aNumEdits ) {
      fLogger.severe(<span class='literal'>"Business rule failure occured. Cannot commit transaction."</span>);
      rollbackTx();
    }
    <span class='keyword'>else</span> {
      fLogger.fine(<span class='literal'>"Commiting transaction."</span>);
      fConnection.commit();
      fConnection.setAutoCommit(fON);
    }
  }
  
  <span class='keyword'>private</span> <span class='keyword'>void</span> rollbackTx() <span class='keyword'>throws</span> DAOException {
    fLogger.severe(<span class='literal'>"ROLLING BACK TRANSACTION."</span>);
    <span class='keyword'>try</span> {
      fConnection.rollback();
    }
    <span class='keyword'>catch</span>(SQLException ex){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> DAOException(<span class='literal'>"Cannot rollback transaction"</span>, ex);
    }
  }
}
 
</PRE>
<br>
<br>Here is an example of using <tt>TxTemplate</tt>. It alters the set of 
roles attached to an end user, first by deleting all existing roles, and 
then by adding the new roles one at a time. 
<br>
<PRE>

<span class='keyword'>final</span> <span class='keyword'>class</span> RoleDAO {

  <span class='comment'>//..elided  
</span>
  <span class='comment'>/**
  * Update all roles attached to a user.
  * 
  * &lt;P&gt;This implementation will treat all edits to user roles as 
  * '&lt;tt&gt;DELETE-ALL&lt;/tt&gt;, then &lt;tt&gt;ADD-ALL&lt;/tt&gt;' operations. 
  */</span>
  <span class='keyword'>boolean</span> change(UserRole aUserRole) <span class='keyword'>throws</span> DAOException {
    Tx update = <span class='keyword'>new</span> UpdateTransaction(aUserRole);
    <span class='keyword'>return</span> Util.isSuccess(update.executeTx());
  }
  
  <span class='comment'>// PRIVATE //
</span>  
  <span class='comment'>/** Cannot be a {@link hirondelle.web4j.database.TxSimple}, since there is looping. */</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>class</span> UpdateTransaction <span class='keyword'>extends</span> TxTemplate {
    UpdateTransaction(UserRole aUserRole){
      <span class='keyword'>super</span>(ConnectionSrc.ACCESS_CONTROL);
      fUserRole = aUserRole;
    }
    <span class='keyword'>public</span> <span class='keyword'>int</span> executeMultipleSqls(
      Connection aConnection
    ) <span class='keyword'>throws</span> SQLException, DAOException {
      <span class='keyword'>int</span> result = <span class='literal'>0</span>;
      <span class='comment'>//perform edits using a shared connection
</span>      result = result + DbTx.edit(aConnection, ROLES_DELETE, fUserRole.getUserName());
      <span class='keyword'>for</span>(Id roleId : fUserRole.getRoles()){
        result = result + DbTx.edit(aConnection,ROLES_ADD,fUserRole.getUserName(),roleId);
      }
      <span class='keyword'>return</span> result;
    }
    <span class='keyword'>private</span> UserRole fUserRole;
  }
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActionc791-2.html?Id=72'>Consider composition instead of subclassing</a> <br>
 
  
  <a href='TopicActionae2d-2.html?Id=139'>Command objects</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='164'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=164 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
